/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gac.gacmod.core;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import org.openide.modules.ModuleInstall;
import org.openide.util.Exceptions;

/**
 * Manages a module's lifecycle. Remember that an installer is optional and
 * often not needed at all.
 */
public class Installer extends ModuleInstall
{

    @Override
    public void restored()
    {
        File pluginDir = new File( "plugins"  + File.separator);

        for( File file: pluginDir.listFiles())
        {
            System.out.println( file.toString());
            addFile( file );
        }
        //addFile("d:\\JavaLibrary3.jar");
        //addFile("d:\\GACAPI.jar");
    }

     public static void addFile(String s)
    {
        File f = new File(s);
        addFile(f);
    }//end method

    public static void addFile(File f)
    {

        try
        {
            addURL(f.toURI().toURL());

            //logger.log("added file : " + f.toString());
        }
        catch (MalformedURLException ex)
        {
            Exceptions.printStackTrace(ex);
        }
    }//end method

    private static final Class<?>[] parameters = new Class<?>[]
    {
        URL.class
    };

    public static void addURL(URL u)
    {

        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<?> sysclass = URLClassLoader.class;

        try
        {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[]
                    {
                        u
                    });
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }//end try catch

    }//end method
}
